#include "s_sc_uart.h"


#include "h_cc2640r2f_define.h"

//#include "s_debug_msg_handle.h"

#define BV(n)                                                   (1 << (n))

#define S_SC_UART_BAUD                                          H_CC2640R2F_DEBUG_BaudRate


#include <icall_ble_api.h>

#define S_SC_UART_Malloc                                        ICall_malloc
#define S_SC_UART_Free                                          ICall_free
    
/*
volatile unsigned int S_SC_UART_GetCount = 0;
unsigned char S_SC_UART_RxBuff[SCIF_UART_RX_FIFO_MAX_COUNT + 1];
*/


void S_SC_UART_WriteBuff(const char* buf, unsigned short len)
{
  //scifUartRxEnable(0);
  scifUartTxPutChars(buf, len);
  //scifUartRxEnable(1);
}

void scCtrlReadyCallback(void)
{
    
}

void scTaskAlertCallback(void)
{
    unsigned char rlen = (unsigned char)scifUartGetRxFifoCount();
    char *rdata = (char *)S_SC_UART_Malloc(sizeof(char) * rlen);
    
    if(NULL == rdata)
    {
//        H_CC2640R2F_UART_Debug("SC ma failed\r\n");
        return;
    }
    
    // Clear the ALERT interrupt source
    scifClearAlertIntSource();
   
    scifUartRxGetChars(rdata, rlen);
    //S_Debug_MSG_Handle((unsigned char*)rdata, rlen);
    
    S_SC_UART_Free(rdata);
    rdata = NULL;
    
    // Clear the events that triggered this
    scifUartClearEvents();

    // Acknowledge the alert event
    scifAckAlertEvents();
    
}

/*
void S_SC_UART_TxConf(void)
{
    //H_CC2640R2F_UART_Debug("The thr is %d\r\n", scifTaskData.uart.cfg.alertTxFifoThr);
    scifTaskData.uart.cfg.alertTxFifoThr = 5;
}
*/

signed char S_SC_UART_Init(void)
{
    // Initialize the Sensor Controller
    scifOsalInit();
    scifOsalRegisterCtrlReadyCallback(scCtrlReadyCallback);
    scifOsalRegisterTaskAlertCallback(scTaskAlertCallback);
    scifInit(&scifDriverSetup);

    // Start the UART emulator
    scifExecuteTasksOnceNbl(BV(SCIF_UART_TASK_ID));

    // Enable baud rate generation
    scifUartSetBaudRate(S_SC_UART_BAUD);

    // Enable RX (10 idle bit periods required before enabling start bit detection)
    
    scifUartSetRxFifoThr(SCIF_UART_RX_FIFO_MAX_COUNT / 2);
    scifUartSetRxTimeout(10 * 2);
    scifUartSetRxEnableReqIdleCount(10 * 2);
    scifUartRxEnable(1);
    
    scifUartSetTxFifoThr(SCIF_UART_TX_FIFO_MAX_COUNT / 2);
    

    // Enable events (half full RX FIFO or 10 bit period timeout
    scifUartSetEventMask(BV_SCIF_UART_ALERT_RX_FIFO_ABOVE_THR | BV_SCIF_UART_ALERT_RX_BYTE_TIMEOUT);
    
    
    
    return 0;
}
